package com.ssyc.main.activity;

import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ssyc.common.base.BaseActivity;
import com.ssyc.common.base.SpKeys;
import com.ssyc.common.manager.PopUpManager;
import com.ssyc.common.utils.PermissionUtil;
import com.ssyc.common.utils.SPUtil;
import com.ssyc.common.utils.ScreenUtils;
import com.ssyc.common.utils.SnackbarUtil;
import com.ssyc.common.utils.UiUtils;
import com.ssyc.main.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色选择界面
 * Created by Administrator on 2018/4/17 0017.
 */
@Route(path = "/main/ChooseRoleActivity")
public class ChooseRoleActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout llMain;
    private LinearLayout llStudent;
    private LinearLayout llTeacher;
    private LinearLayout llParent;
    private LinearLayout llMaster;
    private Button btOK;

    //显示已选择学生的TextView
    private TextView tvShowStudent;
    //显示已选择老师的TextView
    private TextView tvShowTeacher;
    //显示已选择家长的TextView
    private TextView tvShowParent;
    //显示已选择校长的TextView
    private TextView tvShowMaster;

    //用于存放提示的TextView的集合
    private List<TextView> textViews;

    //记录选择的角色类型,0学生,1家长,2老师,3校长
    private int type = -1;

    @Override
    protected boolean isNeedShowTitle() {
        return false;
    }

    @Override
    protected String setTitleText() {
        return null;
    }

    @Override
    protected int getContentLayout() {
        return R.layout.main_activity_choose_role;
    }

    @Override
    protected void init() {
        showContent();

        //初始化视图
        initView();

        //适配的方法处理
        doAdaptiveAction();

        //用户协议和隐私
        startDialog();
//        startAgreePop();

    }


//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus) {
//            LogUtils.iTag("test","走了弹框方法论...");
//            startAgreePop();
//        }
//    }

    /**
     * 初始化视图的方法
     */
    private void initView() {
        llMain = findViewById(R.id.ll_main);
        llStudent = findViewById(R.id.ll_student);
        llStudent.setOnClickListener(this);
        llTeacher = findViewById(R.id.ll_teacher);
        llTeacher.setOnClickListener(this);
        llParent = findViewById(R.id.ll_parent);
        llParent.setOnClickListener(this);
        llMaster = findViewById(R.id.ll_master);
        llMaster.setOnClickListener(this);
        btOK = findViewById(R.id.bt_OK);
        btOK.setEnabled(false);
        btOK.setOnClickListener(this);
        tvShowStudent = findViewById(R.id.tv_show_student);
        tvShowTeacher = findViewById(R.id.tv_show_teacher);
        tvShowParent = findViewById(R.id.tv_show_parent);
        tvShowMaster = findViewById(R.id.tv_show_master);
        textViews = new ArrayList<>();
        textViews.add(tvShowStudent);
        textViews.add(tvShowParent);
        textViews.add(tvShowTeacher);
        textViews.add(tvShowMaster);
    }

    /**
     * 对页面控件做适配处理
     * 屏幕高度-顶部的背景高度100  然后按1:1:1:1:1
     */
    private void doAdaptiveAction() {
        //获取屏幕高度
        int screenHeight = ScreenUtils.getScreenHeight(this);
        //获取屏幕宽度
        int screenWidth = ScreenUtils.getScreenWidth(this);
        //(屏幕高度-顶部高度)然后均分5份,取均分值的3/4
        int itemHeight = (screenHeight - 100) / 5 * 7 / 10;
        //计算宽度
        int itemWidth = screenWidth - (int) getResources().getDimension(R.dimen.main_choose_role_margin) * 2;
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(itemWidth, itemHeight);
        lp.gravity = Gravity.CENTER;
        llStudent.setLayoutParams(lp);
        llTeacher.setLayoutParams(lp);
        llParent.setLayoutParams(lp);
        llMaster.setLayoutParams(lp);
    }


    /**
     * 页面控件点击事件
     *
     * @param view
     */
    @Override
    public void onClick(View view) {
        if (!isDoubleClick(view)) {

            int id = view.getId();
            if (id == R.id.ll_student) {
                //学生
                syncState(0);
            } else if (id == R.id.ll_parent) {
                //家长
                syncState(1);
            } else if (id == R.id.ll_teacher) {
                //老师
                syncState(2);
            } else if (id == R.id.ll_master) {
                //校长
                syncState(3);
            } else if (id == R.id.bt_OK) {
                //确定按钮
                goToMainAction();
            }

        }
    }

    /**
     * 根据选择的角色跳转到不同模块的主界面的方法
     */
    private void goToMainAction() {
        if (type == -1) {
            //证明还没选择就角色
            SnackbarUtil.ShortSnackbar(llMain, "您还没有选择角色", 0).show();
            return;
        } else {
            //证明选择了角色,跳转到登录界面
            UiUtils.startActivity(this, LoginActivity.class);
            finish();
        }
    }


    /**
     * 根据选择的位置控制提示的隐藏与显示
     *
     * @param pos
     */
    private void syncState(int pos) {
        if (!btOK.isEnabled()) {
            btOK.setEnabled(true);
            btOK.setBackgroundResource(R.drawable.main_bt_ok);
        }
        for (int i = 0; i < textViews.size(); i++) {
            if (pos == i) {
                textViews.get(i).setVisibility(View.VISIBLE);
                type = i;
            } else {
                textViews.get(i).setVisibility(View.INVISIBLE);
            }
        }

        if (type == 0) {
            // 保存学生
            SPUtil.put(this, SpKeys.ROLETYPE, 0);
        } else if (type == 1) {
            //保存家长角色
            SPUtil.put(this, SpKeys.ROLETYPE, 1);
        } else if (type == 2) {
            //保存老师角色
            SPUtil.put(this, SpKeys.ROLETYPE, 2);
        } else if (type == 3) {
            //保存校长角色
            SPUtil.put(this, SpKeys.ROLETYPE, 3);
        }

    }


    /**
     * 用户协议与隐私政策的弹窗
     */
    private void startDialog() {
        if (!SPUtil.getBoolean(ChooseRoleActivity.this, "hasAgree")) {

            final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.show();
            alertDialog.setCancelable(false);
            Window window = alertDialog.getWindow();
            if (window != null) {
                window.setContentView(R.layout.dialog_initmate);
                window.setGravity(Gravity.CENTER);

                //设置宽高
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                alertDialog.getWindow().setAttributes(lp);


                TextView tvContent = window.findViewById(R.id.tv_content);
                TextView tvCancel = window.findViewById(R.id.tv_cancel);
                TextView tvAgree = window.findViewById(R.id.tv_agree);
                String str = getResources().getString(R.string.main_yhxy_yszc);

                SpannableStringBuilder ssb = new SpannableStringBuilder();
                ssb.append(str);
                final int start = str.indexOf("《");//第一个出现的位置
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (!isDoubleClick(widget)) {
                            AgreementAndPrivacyActivity.goActivity(ChooseRoleActivity.this, "隐私政策");
                        }
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                        ds.setColor(Color.BLUE);
                    }
                }, start, start + 6, 0);

                int end = str.lastIndexOf("《");
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (!isDoubleClick(widget)) {
                            AgreementAndPrivacyActivity.goActivity(ChooseRoleActivity.this, "用户协议");
                        }
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                        ds.setColor(Color.BLUE);
                    }
                }, end, end + 6, 0);

                tvContent.setMovementMethod(LinkMovementMethod.getInstance());
                tvContent.setText(ssb, TextView.BufferType.SPANNABLE);


                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            alertDialog.cancel();
//                            finish();
                        }
                    }
                });

                tvAgree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //用户点击同意后在SP中保存一个变量值
                            SPUtil.put(ChooseRoleActivity.this, "hasAgree", true);
                            alertDialog.cancel();

                            //权限申请
                            doObtainPermission();
                        }
                    }
                });
            }

        }
    }


    /**
     * 用户协议与隐私政策的弹窗
     */
    private void startAgreePop() {
        PopUpManager.showPopByMatchParent(this, R.layout.main_pop_agree, 0.3f, this, new PopUpManager.onGetViewListener() {
            @Override
            public void getChildView(View view, int layoutResId) {


                TextView tvContent = view.findViewById(R.id.tv_content);
                TextView tvCancel = view.findViewById(R.id.tv_cancel);
                TextView tvAgree = view.findViewById(R.id.tv_agree);
                String str = getResources().getString(R.string.main_yhxy_yszc);

                SpannableStringBuilder ssb = new SpannableStringBuilder();
                ssb.append(str);
                final int start = str.indexOf("《");//第一个出现的位置
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (!isDoubleClick(widget)) {
                            AgreementAndPrivacyActivity.goActivity(ChooseRoleActivity.this, "隐私政策");
                        }
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                        ds.setColor(Color.BLUE);
                    }
                }, start, start + 6, 0);

                int end = str.lastIndexOf("《");
                ssb.setSpan(new ClickableSpan() {
                    @Override
                    public void onClick(@NonNull View widget) {
                        if (!isDoubleClick(widget)) {
                            AgreementAndPrivacyActivity.goActivity(ChooseRoleActivity.this, "用户协议");
                        }
                    }

                    @Override
                    public void updateDrawState(@NonNull TextPaint ds) {
                        super.updateDrawState(ds);
                        ds.setUnderlineText(false);
                        ds.setColor(Color.BLUE);
                    }
                }, end, end + 6, 0);

                tvContent.setMovementMethod(LinkMovementMethod.getInstance());
                tvContent.setText(ssb, TextView.BufferType.SPANNABLE);


                tvCancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            PopUpManager.dismiss();
                        }
                    }
                });

                tvAgree.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isDoubleClick(v)) {
                            //用户点击同意后在SP中保存一个变量值
                            SPUtil.put(ChooseRoleActivity.this, "hasAgree", true);
                            PopUpManager.dismiss();


                            //权限申请
                            doObtainPermission();

                        }
                    }
                });

            }
        });

    }


    /**
     * 申请权限
     */
    private void doObtainPermission() {

        if (Build.VERSION.SDK_INT >= 23 && PermissionUtil.checkPermission(ChooseRoleActivity.this, PermissionUtil.PERMISSIONS_STORAGE).length > 0) {
            PermissionUtil.checkAndRequestPermissions(ChooseRoleActivity.this, PermissionUtil.PERMISSIONS_STORAGE);
        }
    }

    /**
     * 申请权限的回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean hasPermissionDenin = false;
        if (requestCode == PermissionUtil.REQUEST_CODE) {
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[i] == -1) {
                    hasPermissionDenin = true;
                    break;
                }
            }
            if (hasPermissionDenin) {
//                Toast.makeText(this, "未同意所有权限将无法使用相关功能", Toast.LENGTH_LONG).show();
            }
        }
    }
}
